package com.zmn.mcc.admin.controller.staff.dpermit;

import com.zmn.base.channel.common.dro.ChannelDRO;
import com.zmn.base.channel.common.query.ChannelQuery;
import com.zmn.base.channel.dubbo.interfaces.channel.ChannelListRemoteService;
import com.zmn.base.plat.engine.common.constant.PlatEngineConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto2.AMISListData;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.cube.common.dro.measure.MeasureDRO;
import com.zmn.cube.common.dro.menu.MenuDRO;
import com.zmn.cube.dubbo.dto.DubboConsts;
import com.zmn.cube.dubbo.interfaces.measure.MeasureListRemoteService;
import com.zmn.cube.dubbo.interfaces.menu.MenuListRemoteService;
import com.zmn.mcc.common.constant.DpermitConsts;
import com.zmn.mcc.manager.utils.DpermitUtil;
import com.zmn.mcc.model.dto.dpermit.DpermitSimpleDO;
import com.zmn.mcc.model.entity.dpermit.channel.BaseChannelQuery;
import com.zmn.mcc.model.entity.staff.McStaff;
import com.zmn.mcc.model.entity.staff.McStaffDpermit;
import com.zmn.mcc.model.entity.staff.McStaffDpermitQuery;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author heguanghua
 * @since 2020/05/20 12:28
 */
@Controller
@RequestMapping("/staff/dpermit/")
public class StaffDpermitListController extends StaffDpermitBaseController {

    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private MenuListRemoteService menuListRemoteService;

    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private MeasureListRemoteService measureListRemoteService;
    @DubboReference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private ChannelListRemoteService channelCooporationListremoteservice;

    /**
     * 组织权限树状列表
     */
    @RequestMapping("organize/tree")
    public String organizeTree(HttpServletRequest request,
                               @RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                               Model model) {

        McStaff obj = NumberUtil.isNotNullOrZero(staffId) ? staffService.findByKey(staffId) : new McStaff();

        model.addAttribute("obj", obj);

        // 是否拥有"权限管理员角色"
        model.addAttribute("isAssignAdmin", staffBService.isAssignAdmin(getStaffId()));

        return "staff/dpermit/organize/tree";
    }

    @RequestMapping("organize/ajaxTree")
    @ResponseBody
    public ResponseDTO organizeAjaxTree(HttpServletRequest request, HttpServletResponse response,
                                        @RequestParam(value = "staffId", defaultValue = "0") Integer staffId) {

        ResponseDTO result = staffDpermitBService.listOrganizeDpermit(staffId, GlobalDict.STATUS_ENABLE);
        return result;
    }

    /**
     * 推广权限树状列表
     */
    @RequestMapping("account/tree")
    public String accountTree(HttpServletRequest request,
                               @RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                               Model model) {

        McStaff obj = NumberUtil.isNotNullOrZero(staffId) ? staffService.findByKey(staffId) : new McStaff();

        model.addAttribute("obj", obj);

        // 是否拥有"权限管理员角色"
        model.addAttribute("isAssignAdmin", staffBService.isAssignAdmin(getStaffId()));

        return "staff/dpermit/account/tree";
    }

    /**
     * 推广权限树状列表
     */
    @RequestMapping("account/ajaxTree")
    @ResponseBody
    public ResponseDTO accountAjaxTree(HttpServletRequest request, HttpServletResponse response,
                                        @RequestParam(value = "staffId", defaultValue = "0") Integer staffId) {

        ResponseDTO result = staffDpermitBService.listAccountDpermit(staffId, GlobalDict.STATUS_ENABLE);
        return result;
    }

    /**
     * 新渠道权限树状列表
     */
    @RequestMapping("newchannel/tree")
    public String newchannelTree(HttpServletRequest request,
                              @RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                              Model model) {

        McStaff obj = NumberUtil.isNotNullOrZero(staffId) ? staffService.findByKey(staffId) : new McStaff();

        model.addAttribute("obj", obj);

        // 是否拥有"权限管理员角色"
        model.addAttribute("isAssignAdmin", staffBService.isAssignAdmin(getStaffId()));

        return "staff/dpermit/newchannel/tree";
    }

    /**
     * 新渠道权限树状列表
     */
    @RequestMapping("newchannel/ajaxTree")
    @ResponseBody
    public ResponseDTO newchannelAjaxTree(HttpServletRequest request, HttpServletResponse response,
                                       @RequestParam(value = "staffId", defaultValue = "0") Integer staffId) {

        ResponseDTO result = staffDpermitBService.listNewchannelDpermit(staffId, GlobalDict.STATUS_ENABLE);
        return result;
    }

    /**
     * 部门权限树状列表
     */
    @RequestMapping("dept/tree")
    public String deptTree(HttpServletRequest request,
                           @RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                           Model model) {

        McStaff obj = NumberUtil.isNotNullOrZero(staffId) ? staffService.findByKey(staffId) : new McStaff();

        model.addAttribute("obj", obj);

        // 是否拥有"权限管理员角色"
        model.addAttribute("isAssignAdmin", staffBService.isAssignAdmin(getStaffId()));

        return "staff/dpermit/dept/tree";
    }

    @RequestMapping("dept/ajaxTree")
    @ResponseBody
    public ResponseDTO deptAjaxTree(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam(value = "staffId", defaultValue = "0") Integer staffId) {

        ResponseDTO result = staffDpermitBService.listDeptDpermit(staffId, GlobalDict.STATUS_ENABLE);
        return result;
    }

    /**
     * 区域权限树状列表
     */
    @RequestMapping("area/tree")
    public String areaTree(HttpServletRequest request,
                           @RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                           Model model) {

        McStaff obj = NumberUtil.isNotNullOrZero(staffId) ? staffService.findByKey(staffId) : new McStaff();

        model.addAttribute("obj", obj);

        // 是否拥有"权限管理员角色"
        model.addAttribute("isAssignAdmin", staffBService.isAssignAdmin(getStaffId()));

        return "staff/dpermit/area/tree";
    }

    @RequestMapping("area/ajaxTree")
    @ResponseBody
    public ResponseDTO areaAjaxTree(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam(value = "staffId", defaultValue = "0") Integer staffId) {

        ResponseDTO result = staffDpermitBService.listAreaDpermit(staffId, GlobalDict.STATUS_ENABLE);
        return result;
    }

    /**
     * 渠道权限树状列表
     */
    @RequestMapping("channel/tree")
    public String channelTree(HttpServletRequest request,
                              @RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                              Model model) {

        McStaff obj = NumberUtil.isNotNullOrZero(staffId) ? staffService.findByKey(staffId) : new McStaff();

        model.addAttribute("obj", obj);

        // 是否拥有"权限管理员角色"
        model.addAttribute("isAssignAdmin", staffBService.isAssignAdmin(getStaffId()));

        return "staff/dpermit/channel/tree";
    }

    @RequestMapping("channel/ajaxTree")
    @ResponseBody
    public ResponseDTO channelAjaxTree(HttpServletRequest request, HttpServletResponse response,
                                       @RequestParam(value = "staffId", defaultValue = "0") Integer staffId) {

        ResponseDTO result = staffDpermitBService.listChannelDpermit(staffId, GlobalDict.STATUS_ENABLE);
        return result;
    }

    /**
     * 渠道权限列表
     */
    @RequestMapping("channel/list")
    public String channelList(HttpServletRequest request,
                              @ModelAttribute McStaffDpermitQuery query,
                              Model model) {

        String keyword = request.getParameter("keyword");
        if (NumberUtil.isNumber(keyword)) {
            query.setDataId(Integer.parseInt(keyword));
            query.setDataName("");
        } else {
            query.setDataName(keyword);
        }
        query.setDataType(DpermitConsts.TYPE_COOPERATION);
        query.setDataLevel(DpermitConsts.COOPERATION_LEVEL_COMPANY);
        query.setStaffId(query.getStaffId());

        List<McStaffDpermit> dpermits = staffDpermitService.listPageByQuery(query);

        McStaff obj = NumberUtil.isNotNullOrZero(query.getStaffId()) ? staffService.findByKey(query.getStaffId()) : new McStaff();

        McStaffDpermitQuery twoQuery = new McStaffDpermitQuery();
        twoQuery.setStaffId(query.getStaffId());
        twoQuery.setDataParentIds(dpermits.stream().map(item -> item.getDataId()).collect(Collectors.toList()));
        List<McStaffDpermit> channels = staffDpermitService.listByQuery(twoQuery);

        Map<Integer, DpermitSimpleDO> map = new LinkedHashMap<>();
        for (McStaffDpermit dpermit : dpermits) {
            DpermitSimpleDO item = DpermitUtil.parseToDpermitSimpleDO(dpermit);
            map.put(item.getDataId(), item);
        }
        for (McStaffDpermit dpermit : channels) {
            DpermitSimpleDO item = DpermitUtil.parseToDpermitSimpleDO(dpermit);
            DpermitSimpleDO parent = map.get(item.getParentId());
            if (parent != null) {
                parent.getSubors().add(item);
            }
        }

        model.addAttribute("items", map.values());
        model.addAttribute("vo", query);

        model.addAttribute("obj", obj);

        model.addAttribute("keyword", keyword);

        // 是否拥有"权限管理员角色"
        model.addAttribute("isAssignAdmin", staffBService.isAssignAdmin(getStaffId()));

        return "staff/dpermit/channel/list";
    }

    /**
     * 大数据报表权限树状列表
     */
    @RequestMapping("cube/tree")
    public String cubeTree(HttpServletRequest request,
                           @RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                           Model model) {

        McStaff obj = NumberUtil.isNotNullOrZero(staffId) ? staffService.findByKey(staffId) : new McStaff();

        model.addAttribute("obj", obj);
        model.addAttribute("flag", 9);

        // 是否拥有"权限管理员角色"
        model.addAttribute("isAssignAdmin", staffBService.isAssignAdmin(getStaffId()));

        return "staff/dpermit/cube/tree";
    }

    @RequestMapping("cube/ajaxTree")
    @ResponseBody
    public ResponseDTO cubeAjaxTree(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam(value = "staffId", defaultValue = "0") Integer staffId) {

        ResponseDTO<List<MenuDRO>> menusResponse = menuListRemoteService.listAboveByLevel(DpermitConsts.CUBE_LEVEL_FOUR, GlobalDict.STATUS_ENABLE);
        if (!menusResponse.isSuccess()) {
            return ResponseDTO.fail("没有取得菜单列表");
        }
        ResponseDTO result = staffDpermitBService.listCubeDpermit(staffId, GlobalDict.STATUS_ENABLE, menusResponse.getData());
        return result;
    }

    /**
     * 大数据指标权限树状列表
     */
    @RequestMapping("measure/tree")
    public String measureTree(HttpServletRequest request,
                              @RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                              Model model) {

        McStaff obj = NumberUtil.isNotNullOrZero(staffId) ? staffService.findByKey(staffId) : new McStaff();

        model.addAttribute("obj", obj);
        model.addAttribute("flag", 9);

        // 是否拥有"权限管理员角色"
        model.addAttribute("isAssignAdmin", staffBService.isAssignAdmin(getStaffId()));

        return "staff/dpermit/measure/tree";
    }

    @RequestMapping("measure/ajaxTree")
    @ResponseBody
    public ResponseDTO<List<DpermitSimpleDO>> measureAjaxTree(HttpServletRequest request, HttpServletResponse response,
                                                              @RequestParam(value = "staffId", defaultValue = "0") Integer staffId) {

        ResponseDTO<List<MeasureDRO>> measureResponse = measureListRemoteService.listMeasureByDataset(GlobalDict.STATUS_ENABLE);
        if (!measureResponse.isSuccess()) {
            return ResponseDTO.fail("没有取得指标列表");
        }
        ResponseDTO<List<DpermitSimpleDO>> result = staffDpermitBService.listMeasureDpermit(staffId, GlobalDict.STATUS_ENABLE, measureResponse.getData());
        return result;
    }

    /**
     * 产品权限树状列表
     */
    @RequestMapping("product/tree")
    public String productTree(HttpServletRequest request,
                              @RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                              Model model) {

        McStaff obj = NumberUtil.isNotNullOrZero(staffId) ? staffService.findByKey(staffId) : new McStaff();

        model.addAttribute("obj", obj);

        // 是否拥有"权限管理员角色"
        model.addAttribute("isAssignAdmin", staffBService.isAssignAdmin(getStaffId()));

        return "staff/dpermit/product/tree";
    }

    @RequestMapping("product/ajaxTree")
    @ResponseBody
    public ResponseDTO productAjaxTree(HttpServletRequest request, HttpServletResponse response,
                                       @RequestParam(value = "staffId", defaultValue = "0") Integer staffId) {

        ResponseDTO result = staffDpermitBService.listProductDpermit(staffId, GlobalDict.STATUS_ENABLE);
        return result;
    }

    /**
     * 合作查询
     */
    @RequestMapping(value = "account/list")
    public String list(HttpServletRequest request,
                       @RequestParam(value = "keyId", defaultValue = "0") Integer keyId,            // 主ID，用于回调方法读写相关数据
                       @RequestParam(value = "callbackUrl", defaultValue = "") String callbackUrl,  // 回调方法的url
                       @RequestParam(value = "multi", defaultValue = "1") Integer multi,            // 是否允许多选，1不允许，2允许
                       @ModelAttribute BaseChannelQuery query,
                       Model model) {

        String keyword = request.getParameter("keyword");
        ChannelQuery channelQuery = new ChannelQuery();
        if(StringUtil.isNotBlank(keyword)){
            channelQuery.setKeyword(keyword);
        }
        channelQuery.setPageIndex(query.getPageIndex());
        channelQuery.setPageSize(query.getPageSize());
        //channelQuery.setRank(NumberUtil.isNullOrZero(query.getLevel())?null:query.getLevel());
        channelQuery.setStatus(PlatEngineConsts.STATUS_VALID);
        channelQuery.setRank(GlobalConsts.LEVEL_2);
        if(NumberUtil.isNotNullOrZero(query.getAbutmentDeptId())){
            channelQuery.setAbutmentDeptId(query.getAbutmentDeptId());
        }
        ResponseDTO<AMISListData<ChannelDRO>> responseDTO = channelCooporationListremoteservice.listPageByQuery(channelQuery);
        List<ChannelDRO> items = new ArrayList<>();
        if (responseDTO.isSuccess()) {
            AMISListData<ChannelDRO> channelListPageDRO = responseDTO.getData();
            query.setTotalCount(channelListPageDRO.getTotal());
            items.addAll(channelListPageDRO.getItems());
        }


        model.addAttribute("items", items);
        model.addAttribute("vo", query);

        model.addAttribute("keyword", keyword);

        model.addAttribute("keyId", keyId);
        model.addAttribute("callbackUrl", callbackUrl);
        model.addAttribute("multi", multi);
        model.addAttribute("type", query.getType());

        return "staff/dpermit/account/list";
    }
}
